<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择权限类型" clearable>
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增
          </el-button>
          <el-button type="success" @click="handleExpandAll">
            <el-icon><Expand /></el-icon>展开/折叠
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="permList"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="权限名称" min-width="180" />
        <el-table-column prop="code" label="权限编码" min-width="180" />
        <el-table-column prop="type" label="权限类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.type === 'menu' ? 'primary' : 'success'">
              {{ row.type === 'menu' ? '菜单' : '按钮' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路由路径" min-width="150" show-overflow-tooltip />
        <el-table-column prop="component" label="组件路径" min-width="180" show-overflow-tooltip />
        <el-table-column prop="icon" label="图标" width="80" align="center">
          <template #default="{ row }">
            <el-icon v-if="row.icon">
              <component :is="row.icon" />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleAdd(row)">
              <el-icon><Plus /></el-icon>新增
            </el-button>
            <el-button type="primary" link @click="handleUpdate(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑权限对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="permFormRef"
        :model="permForm"
        :rules="permRules"
        label-width="100px"
      >
        <el-form-item label="上级权限" prop="parent_id">
          <el-tree-select
            v-model="permForm.parent_id"
            :data="permOptions"
            placeholder="请选择上级权限"
            :props="{ label: 'name', value: 'id', children: 'children' }"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="permForm.type">
            <el-radio label="menu">菜单</el-radio>
            <el-radio label="button">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permForm.code" placeholder="请输入权限编码" />
        </el-form-item>
        
        <template v-if="permForm.type === 'menu'">
          <el-form-item label="路由路径" prop="path">
            <el-input v-model="permForm.path" placeholder="请输入路由路径" />
          </el-form-item>
          <el-form-item label="组件路径" prop="component">
            <el-input v-model="permForm.component" placeholder="请输入组件路径" />
          </el-form-item>
          <el-form-item label="图标" prop="icon">
            <el-input v-model="permForm.icon" placeholder="请输入图标名称" />
          </el-form-item>
        </template>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="permForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="permForm.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Expand } from '@element-plus/icons-vue'
import { useThemeStore } from '@/store/theme'
import { getPermissions, getPermissionTree, getPermission, createPermission, updatePermission, deletePermission } from '@/api/permission'

// 查询参数
const queryParams = reactive({
  name: '',
  code: '',
  type: '',
  status: null
})

// 表格数据
const permList = ref([])
const loading = ref(false)
const isExpandAll = ref(true)

// 权限树形选项
const permOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 update
const dialogTitle = ref('添加权限')
const permFormRef = ref(null)
const queryFormRef = ref(null)

// 权限表单
const permForm = reactive({
  id: null,
  parent_id: null,
  type: 'menu',
  name: '',
  code: '',
  path: '',
  component: '',
  icon: '',
  sort: 0,
  status: true
})

// 表单校验规则
const permRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  path: [
    { required: false, message: '请输入路由路径', trigger: 'blur' }
  ],
  component: [
    { required: false, message: '请输入组件路径', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 监听权限类型变化，重置相关字段
watch(() => permForm.type, (newType) => {
  if (newType === 'button') {
    permForm.path = ''
    permForm.component = ''
    permForm.icon = ''
  }
})

// 获取权限列表
const getPermList = async () => {
  loading.value = true
  try {
    const res = await getPermissionTree(queryParams)
    permList.value = res.data
  } catch (error) {
    console.error('获取权限列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取权限树形数据（用于选择上级权限）
const getPermTreeData = async () => {
  try {
    const res = await getPermissionTree()
    permOptions.value = [{ id: 0, name: '顶级权限', children: res.data }]
  } catch (error) {
    console.error('获取权限树形数据失败:', error)
  }
}

// 查询
const handleQuery = () => {
  getPermList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 展开/折叠
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
  permList.value = [...permList.value]
}

// 添加权限
const handleAdd = (row) => {
  resetPermForm()
  dialogType.value = 'add'
  dialogTitle.value = '添加权限'
  
  if (row && row.id) {
    // 如果是添加子权限，设置父权限ID
    permForm.parent_id = row.id
    
    // 如果父权限是按钮，不允许添加子权限
    if (row.type === 'button') {
      ElMessage.warning('按钮权限下不能添加子权限')
      return
    }
  }
  
  dialogVisible.value = true
}

// 编辑权限
const handleUpdate = async (row) => {
  resetPermForm()
  dialogType.value = 'update'
  dialogTitle.value = '编辑权限'
  
  try {
    const res = await getPermission(row.id)
    const permData = res.data
    
    // 填充表单数据
    permForm.id = permData.id
    permForm.parent_id = permData.parent_id
    permForm.type = permData.type
    permForm.name = permData.name
    permForm.code = permData.code
    permForm.path = permData.path || ''
    permForm.component = permData.component || ''
    permForm.icon = permData.icon || ''
    permForm.sort = permData.sort
    permForm.status = permData.status
    
    dialogVisible.value = true
  } catch (error) {
    console.error('获取权限详情失败:', error)
    ElMessage.error('获取权限详情失败')
  }
}

// 删除权限
const handleDelete = (row) => {
  // 检查是否有子权限
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该权限下存在子权限，无法删除')
    return
  }
  
  ElMessageBox.confirm(`确认删除权限 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deletePermission(row.id)
      ElMessage.success('删除成功')
      getPermList()
    } catch (error) {
      console.error('删除权限失败:', error)
      ElMessage.error('删除权限失败')
    }
  }).catch(() => {})
}

// 重置权限表单
const resetPermForm = () => {
  permForm.id = null
  permForm.parent_id = null
  permForm.type = 'menu'
  permForm.name = ''
  permForm.code = ''
  permForm.path = ''
  permForm.component = ''
  permForm.icon = ''
  permForm.sort = 0
  permForm.status = true
  
  if (permFormRef.value) {
    permFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  permFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 创建权限
          await createPermission(permForm)
          ElMessage.success('添加成功')
        } else {
          // 更新权限
          await updatePermission(permForm.id, permForm)
          ElMessage.success('更新成功')
        }
        
        dialogVisible.value = false
        getPermList()
        getPermTreeData() // 更新权限树形数据
      } catch (error) {
        console.error('保存权限失败:', error)
        ElMessage.error('保存权限失败')
      }
    }
  })
}

onMounted(() => {
  getPermList()
  getPermTreeData()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;
  
  .search-wrapper {
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 16px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 6px;
            background-color: var(--card-bg-color);
          }
        }
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
  }
  
  .table-wrapper {
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__header) {
      background-color: var(--header-bg-color);
      border-bottom: 1px solid var(--border-color);
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-table) {
      border-radius: 6px;
      overflow: hidden;
      background-color: var(--card-bg-color);
      
      .el-table__header {
        th {
          background-color: var(--header-bg-color);
          color: var(--text-color);
          font-weight: 600;
          border-bottom: 1px solid var(--border-color);
        }
      }
      
      .el-table__body {
        tr {
          background-color: var(--card-bg-color);
          
          &:hover > td {
            background-color: var(--hover-bg-color) !important;
          }
          
          td {
            border-bottom: 1px solid var(--border-color);
            color: var(--text-color);
            
            .el-tag {
              border-radius: 4px;
              font-weight: 500;
            }
            
            .el-button {
              border-radius: 4px;
              font-weight: 500;
              transition: all 0.3s ease;
              color: var(--text-color);
              
              &:hover {
                transform: translateY(-1px);
              }
            }
            
            .el-icon {
              color: var(--text-color);
              font-size: 16px;
            }
          }
        }
      }
      
      // 树形表格特殊样式
      .el-table__expand-icon {
        color: #409eff;
        transition: all 0.3s ease;
        
        &:hover {
          color: #66b1ff;
        }
      }
      
      .el-table__indent {
        border-left: 1px dashed var(--border-color);
      }
    }
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  background-color: var(--card-bg-color);
  
  .el-dialog__header {
    background-color: var(--header-bg-color);
    border-bottom: 1px solid var(--border-color);
    border-radius: 8px 8px 0 0;
    
    .el-dialog__title {
      color: var(--text-color);
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    background-color: var(--card-bg-color);
    padding: 24px;
    color: var(--text-color);
    
    .el-form {
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper,
        .el-tree-select .el-input__wrapper {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-input-number {
          .el-input__wrapper {
            border-radius: 6px;
            background-color: var(--card-bg-color);
          }
        }
        
        .el-radio-group {
          .el-radio {
            margin-right: 20px;
            
            .el-radio__label {
              color: var(--text-color);
            }
          }
        }
      }
    }
  }
  
  .el-dialog__footer {
    background-color: var(--header-bg-color);
    border-top: 1px solid var(--border-color);
    border-radius: 0 0 8px 8px;
    
    .dialog-footer {
      .el-button {
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}

// 树形选择器下拉面板样式
:deep(.el-tree-select__popper) {
  .el-tree {
    background-color: var(--card-bg-color);
    
    .el-tree-node {
      .el-tree-node__content {
        border-radius: 4px;
        transition: all 0.3s ease;
        
        &:hover {
          background-color: var(--hover-bg-color);
        }
      }
      
      .el-tree-node__label {
        color: var(--text-color);
        font-weight: 500;
      }
    }
  }
}
</style>
